package com.example.munidingwei

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import androidx.core.content.ContextCompat

/**
 * 保活助手
 * 帮助应用减少被系统杀死的可能性
 */
object KeepAliveHelper {
    
    private const val TAG = "KeepAliveHelper"
    
    /**
     * 检查是否在电池优化白名单中
     */
    fun isIgnoringBatteryOptimizations(context: Context): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
            val packageName = context.packageName
            return powerManager.isIgnoringBatteryOptimizations(packageName)
        }
        return true
    }
    
    /**
     * 请求加入电池优化白名单
     */
    @SuppressLint("BatteryLife")
    fun requestIgnoreBatteryOptimizations(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!isIgnoringBatteryOptimizations(context)) {
                try {
                    val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                    intent.data = Uri.parse("package:${context.packageName}")
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(intent)
                    
                    Log.d(TAG, "✅ 已请求电池优化白名单")
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 请求电池优化白名单失败: ${e.message}")
                    
                    // 如果直接请求失败，跳转到设置页面
                    try {
                        val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        context.startActivity(intent)
                    } catch (e2: Exception) {
                        Log.e(TAG, "❌ 跳转到设置页面失败: ${e2.message}")
                    }
                }
            } else {
                Log.d(TAG, "✅ 已在电池优化白名单中")
            }
        }
    }
    
    /**
     * 打开自启动管理页面（不同厂商）
     */
    fun openAutoStartSettings(context: Context) {
        val manufacturer = Build.MANUFACTURER.lowercase()
        
        try {
            val intent = when {
                manufacturer.contains("xiaomi") -> {
                    // 小米
                    Intent().apply {
                        setClassName(
                            "com.miui.securitycenter",
                            "com.miui.permcenter.autostart.AutoStartManagementActivity"
                        )
                    }
                }
                manufacturer.contains("oppo") -> {
                    // OPPO
                    Intent().apply {
                        setClassName(
                            "com.coloros.safecenter",
                            "com.coloros.safecenter.permission.startup.StartupAppListActivity"
                        )
                    }
                }
                manufacturer.contains("vivo") -> {
                    // vivo
                    Intent().apply {
                        setClassName(
                            "com.vivo.permissionmanager",
                            "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"
                        )
                    }
                }
                manufacturer.contains("huawei") || manufacturer.contains("honor") -> {
                    // 华为/荣耀
                    Intent().apply {
                        setClassName(
                            "com.huawei.systemmanager",
                            "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity"
                        )
                    }
                }
                manufacturer.contains("meizu") -> {
                    // 魅族
                    Intent().apply {
                        setClassName(
                            "com.meizu.safe",
                            "com.meizu.safe.security.SHOW_APPSEC"
                        )
                        addCategory(Intent.CATEGORY_DEFAULT)
                        putExtra("packageName", context.packageName)
                    }
                }
                manufacturer.contains("samsung") -> {
                    // 三星
                    Intent().apply {
                        setClassName(
                            "com.samsung.android.lool",
                            "com.samsung.android.sm.ui.battery.BatteryActivity"
                        )
                    }
                }
                else -> {
                    // 通用设置页面
                    Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                        data = Uri.fromParts("package", context.packageName, null)
                    }
                }
            }
            
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
            
            Log.d(TAG, "✅ 已打开自启动设置页面: $manufacturer")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开自启动设置失败: ${e.message}")
            
            // 如果失败，打开应用详情页
            try {
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = Uri.fromParts("package", context.packageName, null)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
            } catch (e2: Exception) {
                Log.e(TAG, "❌ 打开应用详情页失败: ${e2.message}")
            }
        }
    }
    
    /**
     * 打开后台运行权限设置
     */
    fun openBackgroundSettings(context: Context) {
        try {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.data = Uri.fromParts("package", context.packageName, null)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
            
            Log.d(TAG, "✅ 已打开应用详情页面")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开应用详情页失败: ${e.message}")
        }
    }
    
    /**
     * 获取保活建议（根据厂商）
     */
    fun getKeepAliveSuggestions(context: Context): List<String> {
        val suggestions = mutableListOf<String>()
        val manufacturer = Build.MANUFACTURER.lowercase()
        
        // 通用建议
        suggestions.add("1. 将应用加入电池优化白名单")
        suggestions.add("2. 允许应用开机自启动")
        suggestions.add("3. 允许应用后台运行")
        suggestions.add("4. 锁定应用到最近任务列表")
        
        // 厂商特定建议
        when {
            manufacturer.contains("xiaomi") -> {
                suggestions.add("\n小米系统特别设置：")
                suggestions.add("- 设置 > 应用设置 > 应用管理 > 定位App")
                suggestions.add("- 开启「自启动」")
                suggestions.add("- 省电策略设置为「无限制」")
                suggestions.add("- 开启「后台弹出界面」")
            }
            manufacturer.contains("oppo") -> {
                suggestions.add("\nOPPO系统特别设置：")
                suggestions.add("- 设置 > 应用管理 > 定位App")
                suggestions.add("- 开启「允许自启动」")
                suggestions.add("- 开启「允许关联启动」")
                suggestions.add("- 开启「允许后台活动」")
            }
            manufacturer.contains("vivo") -> {
                suggestions.add("\nvivo系统特别设置：")
                suggestions.add("- 设置 > 更多设置 > 应用管理 > 定位App")
                suggestions.add("- 开启「自启动」")
                suggestions.add("- 后台耗电选择「允许后台高耗电」")
            }
            manufacturer.contains("huawei") || manufacturer.contains("honor") -> {
                suggestions.add("\n华为/荣耀系统特别设置：")
                suggestions.add("- 设置 > 应用 > 应用启动管理 > 定位App")
                suggestions.add("- 关闭「自动管理」")
                suggestions.add("- 手动开启「自动启动」\"后台活动\"\"关联启动\"")
            }
        }
        
        return suggestions
    }
    
    /**
     * 保存自启动配置
     */
    fun saveAutoStartPreference(context: Context, enabled: Boolean) {
        val prefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
        prefs.edit().putBoolean("auto_start_enabled", enabled).apply()
        
        Log.d(TAG, "自启动配置已保存: $enabled")
    }
    
    /**
     * 获取自启动配置
     */
    fun getAutoStartPreference(context: Context): Boolean {
        val prefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
        return prefs.getBoolean("auto_start_enabled", true)
    }
}



